/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JCameraDialog.java
 *
 * Created on 2009-9-22, 9:38:02
 */

package cn.ekuma.epos.swing.camera;

//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGEncodeParam;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class JCameraDialog extends javax.swing.JDialog {

    private  Player player;
    private CaptureDeviceInfo device;
    private MediaLocator locator ;
    private Buffer buffer;
    private BufferToImage b2i;
    private Image image;
    private BufferedImage retImage;
    private ImageIcon iicon = new ImageIcon();
    boolean proportion = true;
    String str1 = "vfw:DirectSoundCapture:0";
    String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
    Component component1;
    boolean isOK;
    
    /** Creates new form JCameraDialog */
    public JCameraDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
         initComponents();
    }

    
    public JCameraDialog(java.awt.Dialog  parent, boolean modal) {
        super(parent, modal);
         initComponents();
    }

    public void init() throws IOException, NoPlayerException, CannotRealizeException{
       
        player = null;
        device = null;
        locator = null;
        buffer = null;
        b2i = null;
        retImage=null;
        isOK=false;
        component1 = Box.createGlue();
        //=====================初始化设备===================//
         component1.addNotify();
         device = CaptureDeviceManager.getDevice(str2);
         locator = device.getLocator();
         player = Manager.createRealizedPlayer(locator);
         player.start();

         if ((component1 = player.getVisualComponent()) != null) {
                jPanel2.add(component1,java.awt.BorderLayout.CENTER);
          }
         
         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }


    public static JCameraDialog getCameraDialog(Component parent, boolean modal){
        Window window = getWindow(parent);
        JCameraDialog myMsg;
        if (window instanceof Frame) {
            myMsg = new JCameraDialog((Frame) window, true);
        } else {
            myMsg = new JCameraDialog((Dialog) window, true);
        }
        myMsg.applyComponentOrientation(parent.getComponentOrientation());
        return myMsg;
    }


     private static Window getWindow(Component parent) {
        if (parent == null) {
            return new JFrame();
        } else if (parent instanceof Frame || parent instanceof Dialog) {
            return (Window) parent;
        } else {
            return getWindow(parent.getParent());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jOkButton = new javax.swing.JButton();
        jCancelButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jCut = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setPreferredSize(new java.awt.Dimension(500, 262));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setPreferredSize(new java.awt.Dimension(400, 262));
        jPanel2.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel6.setPreferredSize(new java.awt.Dimension(136, 50));

        jOkButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        jOkButton.setAlignmentY(0.0F);
        jOkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jOkButtonActionPerformed(evt);
            }
        });

        jCancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        jCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jOkButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCancelButton)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jOkButton)
                    .addComponent(jCancelButton))
                .addContainerGap())
        );

        jPanel4.add(jPanel6, java.awt.BorderLayout.SOUTH);

        jPanel3.setLayout(new java.awt.GridBagLayout());

        jCut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/search22.png"))); // NOI18N
        jCut.setAlignmentY(0.0F);
        jCut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCutActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 1;
        gridBagConstraints.ipady = 1;
        jPanel3.add(jCut, gridBagConstraints);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/filesave.png"))); // NOI18N
        jButton1.setMaximumSize(new java.awt.Dimension(55, 31));
        jButton1.setMinimumSize(new java.awt.Dimension(55, 31));
        jButton1.setPreferredSize(new java.awt.Dimension(55, 31));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        jPanel3.add(jButton1, gridBagConstraints);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel1.setPreferredSize(new java.awt.Dimension(110, 100));
        jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
        jPanel3.add(jLabel1, gridBagConstraints);

        jPanel4.add(jPanel3, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel4, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-427)/2, (screenSize.height-281)/2, 427, 281);
    }// </editor-fold>//GEN-END:initComponents

    private void jCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCutActionPerformed
        jCutAction();
}//GEN-LAST:event_jCutActionPerformed

    private void jOkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jOkButtonActionPerformed
        okAction();
}//GEN-LAST:event_jOkButtonActionPerformed

    private void jCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelButtonActionPerformed
       cancelAction();
}//GEN-LAST:event_jCancelButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       jSaveAction();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JCameraDialog dialog = new JCameraDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }


   void jCutAction() {
        iicon = new ImageIcon();
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl(
                "javax.media.control.FrameGrabbingControl");
        buffer = fgc.grabFrame(); // 获取当前祯并存入Buffer类
        b2i = new BufferToImage((VideoFormat) buffer.getFormat());
        image = b2i.createImage(buffer); // show the image
        iicon = new ImageIcon();
        /* Toolkit tk = Toolkit.getDefaultToolkit();
        Applet app = new Applet();
        MediaTracker mt = new MediaTracker(app);*/
        //iicon.setImage(resize(85, 95, image, true));
        iicon.setImage(resizeImage(105, 115, getImage()));
        jLabel1.setIcon(iicon);
        jLabel1.setText("W: "+image.getWidth(null)+" *H: "+image.getHeight(null));
    }

    void jSaveAction() {
        JFileChooser filechooser = new JFileChooser();
        filechooser.setFileHidingEnabled(true);

        filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = filechooser.showSaveDialog(null);
        if (result == JFileChooser.CANCEL_OPTION) {
            return;
        }
        File file = filechooser.getSelectedFile();
        if (file == null || file.getName().equals("")) {
            JOptionPane.showMessageDialog(null, "无效的文件名", "警告",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            String s = file.getAbsolutePath();

            BufferedImage bi = (BufferedImage) createImage(image.getWidth(null),
                    image.getHeight(null));
            Graphics2D g2 = bi.createGraphics();
            g2.drawImage(image, null, null);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(s);
            } catch (java.io.FileNotFoundException io) {
                System.out.println("File Not Found");
            }

            /*JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
            param.setQuality(1f, false); //不压缩图像
            encoder.setJPEGEncodeParam(param);
            try {
                encoder.encode(bi);
                out.close();
            } catch (java.io.IOException io) {
                System.out.println("IOException");
            }*/
        }
    }

    private BufferedImage resizeImage(int maxwidth, int maxheight,BufferedImage img) {

        int myheight = img.getHeight();
        int mywidth = img.getWidth();

        if (myheight > maxheight) {
            mywidth = (int) (mywidth * maxheight / myheight);
            myheight = maxheight;
        }
        if (mywidth > maxwidth) {
            myheight = (int) (myheight * maxwidth / mywidth);
            mywidth = maxwidth;
        }

        BufferedImage thumb = new BufferedImage(mywidth, myheight, BufferedImage.TYPE_4BYTE_ABGR);

        double scalex = (double) mywidth / (double) img.getWidth(null);
        double scaley = (double) myheight / (double) img.getHeight(null);

        Graphics2D g2d = thumb.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        g2d.setColor(new Color(0, 0, 0, 0)); // Transparent

        g2d.fillRect(0, 0, mywidth, myheight);
        if (scalex < scaley) {
            g2d.drawImage(img, 0,(int) ((myheight - img.getHeight(null) * scalex) / 2.0)
            , mywidth, (int) (img.getHeight(null) * scalex),  null);
        } else {
           g2d.drawImage(img, (int) ((mywidth - img.getWidth(null) * scaley) / 2.0), 0
           , (int) (img.getWidth(null) * scaley), myheight, null);
        }
        g2d.dispose();

        return thumb;
    }
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jCancelButton;
    private javax.swing.JButton jCut;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jOkButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel6;
    // End of variables declaration//GEN-END:variables


    private void okAction() {
        if(image!=null){
            retImage=getImage();
            isOK=true;
        }
        closeDriver();
        dispose();
    }

    private void cancelAction() {
        closeDriver();
        dispose();
    }

    public BufferedImage getImage() {
        BufferedImage bi = (BufferedImage) createImage(image.getWidth(null),image.getHeight(null));
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(image, null, null);
        g2.dispose();
        return bi;
    }

    public boolean isOK() {
        return isOK;
    }

    public BufferedImage getRetImage() {
        return retImage;
    }

    private void closeDriver() {
        player.close();
        device = null;
        player = null;
        locator = null;
        buffer = null;
        b2i = null;
    }
}
